package heven.holt.wan.android.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.cachedIn
import androidx.paging.filter
import dagger.hilt.android.lifecycle.HiltViewModel
import heven.holt.wan.android.model.UserCoinInfo
import heven.holt.wan.android.repository.WanCoinRepository
import kotlinx.coroutines.flow.map
import javax.inject.Inject

@HiltViewModel
class CoinRankViewModel @Inject constructor(
    wanCoinRepository: WanCoinRepository
) : ViewModel() {
    val topRankMap = MutableLiveData<Map<Int, UserCoinInfo>>()
    private val _topRankMap = mutableMapOf<Int, UserCoinInfo>()

    val flow = wanCoinRepository.getCoinRankListFlow().map {
        it.filter { userCoinInfo ->
            if (userCoinInfo.rank ?: 0 <= 3) {
                _topRankMap[userCoinInfo.rank ?: 0] = userCoinInfo
                if (userCoinInfo.rank ?: 0 == 3) {
                    topRankMap.postValue(_topRankMap)
                }
            }

            userCoinInfo.rank ?: 0 > 3
        }
    }.cachedIn(viewModelScope)
}